package com.webserver.core;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.*;
import java.net.Socket;

/**
 * 线程任务
 * 负责与特定的客户端进行HTTP交互
 */
public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket){
        this.socket=socket;
    }

    @Override
    public void run() {
        try {
            /*
            http://localhost:8088/myweb/index.html
            http://localhost:8088/myweb/classTable.html
             */
            //1解析请求
            HttpServletRequest request=new HttpServletRequest(socket);
            HttpServletResponse response=new HttpServletResponse(socket);

            //2处理请求
            //通过request获取请求中的抽象路径
            String path=request.getUri();//     /myweb/index.html

            //将./webapps/myweb/index.html响应给浏览器
            File file=new File("./webapps"+path);

            if(file.isFile()){//如果定位的是文件
                response.setEntity(file);
            }else{//不是文件（要么不存在，要么是目录，404情况）
                file = new File("./webapps/root/404.html");
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                response.setEntity(file);
            }
            /*
                HTTP/1.1 200 OK(CRLF)
                Content-Type: text/html(CRLF)
                Content-Length: 2546(CRLF)(CRLF)
                1011101010101010101......
             */
            //3发送响应
            response.response();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //响应后断开连接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
